<template>
  <el-dialog @close="tjqdhtCancel('tjqdhtRuleForm')" :close-on-click-modal="false" title="提交签订合同"
    :visible.sync="tjqdhtVisible" width="900px">
    <div class="scroll-view">
      <el-form :model="tjqdhtRuleForm" :rules="tjqdhtRules" ref="tjqdhtRuleForm" :inline="true" label-position="left">
        <el-form-item label="签约日期" prop="signing_date">
          <el-date-picker class="input-box" v-model="tjqdhtRuleForm.signing_date" type="date" clearable
            placeholder="选择日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="签约公司" prop="signing_company_id">
          <el-select filterable class="input-box" v-model="tjqdhtRuleForm.signing_company_id" placeholder="请选择"
            clearable>
            <el-option v-for="item in companyOptions" :key="item.id" :label="item.account_name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开工日期" prop="contract_commencement_date">
          <el-date-picker class="input-box" :picker-options="pickerOptionsEnd"
            v-model="tjqdhtRuleForm.contract_commencement_date" type="date" clearable placeholder="选择日期"
            value-format="yyyy-MM-dd" @change="tjqdhtDataFunc($event, 'start')">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="完工日期" prop="contract_completion_date">
          <el-date-picker class="input-box" :picker-options="pickerOptions_"
            :disabled="!tjqdhtRuleForm.contract_commencement_date" v-model="tjqdhtRuleForm.contract_completion_date"
            type="date" clearable placeholder="选择日期" value-format="yyyy-MM-dd" @change="tjqdhtDataFunc($event, 'end')">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="工期" prop="duration_days" v-if="tjqdhtRuleForm.duration_days">
          <el-input class="input-box" v-model="tjqdhtRuleForm.duration_days" disabled><span
              slot="suffix">天</span></el-input>
        </el-form-item>
        <el-form-item label="最终报价金额" prop="quotation_amount">
          <el-input class="input-box" v-model="tjqdhtRuleForm.quotation_amount" v-input-limit="2" clearable disabled
            @input="quotationRatioFunc"></el-input>
        </el-form-item>
        <el-form-item label="签约金额" prop="contract_price">
          <el-input class="input-box" v-model="tjqdhtRuleForm.contract_price" v-input-limit="2" clearable disabled
            @input="quotationRatioFunc"></el-input>
        </el-form-item>
        <el-form-item label="签约报价比" prop="contract_price">
          <el-input disabled class="input-box" v-model="tjqdhtRuleForm.contract_quotation_ratio" v-input-limit="2"
            clearable>
            <span slot="suffix">%</span>
          </el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input :rows="4" class="input-box" v-model="tjqdhtRuleForm.remark" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="合同附件 (.zip,.ppt,.ppsx,.pptx,.pdf)" prop="contract_file">
          <el-input style="position: absolute; z-index: 0; top: -999999px"
            v-model="tjqdhtRuleForm.contract_file.length"></el-input>
          <el-upload accept=".zip,.ppt,.ppsx,.pptx,pdf" :on-change="(file, fileList) => {
              tjqdhtChangeFile(file, fileList, 'contract_file');
            }
            " :on-remove="(file, fileList) => {
                tjqdhtFileRemove(file, fileList, 'contract_file');
              }
              " :auto-upload="false" :file-list="tjqdhtRuleForm.contract_file" action="#">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer">
      <el-button type="primary" @click="tjqdhtSubmit('tjqdhtRuleForm')" :disabled="diaLoading"
        :loading="diaLoading">提交</el-button>
      <el-button @click="tjqdhtCancel('tjqdhtRuleForm')">关闭</el-button>
    </span>
  </el-dialog>
</template>
<script>
import projectApi from "@/api/projectApi";
import companyApi from "@/api/companyApi";
import adminApi from "@/api/adminApi";
import { getUserInfo } from "@/utils/auth";
import foremanApi from "@/api/foremanApi";

export default {
  name: "",
  props: {
    addDialogVisible: {
      type: Boolean,
      default: false,
      required: false,
    },
    project_id: {
      required: false,
    },
    zjData: {
      required: false,
    },
    dkData: {
      required: false,
    },
  },
  data() {
    var contract_file = (rule, value, callback) => {
      if (!value.length) {
        callback(new Error("请上传合同文件"));
      } else {
        callback();
      }
    };
    return {
      pickerOptionsStart: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      pickerOptionsEnd: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
      pickerOptions_: {},
      tjqdhtVisible: false,
      tjqdhtRuleForm: {
        remark: "",
        signing_date: "",
        signing_company_id: "",
        contract_commencement_date: "",
        contract_completion_date: "",
        duration_days: "",
        quotation_amount: "",
        contract_price: "",
        contract_file: [],
        contract_quotation_ratio: "",
      },
      tjqdhtRules: {
        signing_date: [
          { required: true, message: "请选择签约日期", trigger: "change" },
        ],
        signing_company_id: [
          { required: true, message: "请选择签约公司", trigger: "change" },
        ],
        contract_commencement_date: [
          { required: true, message: "请选择开工日期", trigger: "change" },
        ],
        contract_completion_date: [
          { required: true, message: "请选择完工日期", trigger: "change" },
        ],
        duration_days: "",
        quotation_amount: [
          { required: true, message: "请输入最终报价金额", trigger: "change" },
        ],
        contract_price: [
          { required: true, message: "请输入签约金额", trigger: "change" },
        ],
        contract_file: {
          required: true,
          validator: contract_file,
          trigger: "change",
        },
      },
      companyOptions: [], //公司列表
      diaLoading: false,
    };
  },
  watch: {
    addDialogVisible(val1, val2) {
      if (this.addDialogVisible) {
        this.tjqdhtRuleForm.contract_commencement_date = this.zjData.start_date;
        this.tjqdhtRuleForm.contract_completion_date = this.zjData.end_date;
        const date1 = new Date(this.zjData.start_date);
        const date2 = new Date(this.zjData.end_date);
        this.tjqdhtRuleForm.duration_days = this.daysBetween(date1, date2) + 1;
        this.getCompanyList(1);
        const now = new Date();
        const year = now.getFullYear();
        const month = now.getMonth() + 1; // 月份从0开始，需要加1
        const day = now.getDate();
        console.log(year, month, day);
        this.tjqdhtRuleForm.signing_date = `${year}-${month}-${day}`;
        this.tjqdhtRuleForm.contract_price = Number(this.dkData.new_amount);
        this.tjqdhtRuleForm.quotation_amount = Number(
          this.zjData.quotation_amount
        );
        this.tjqdhtRuleForm.contract_quotation_ratio = (
          (Number(this.dkData.new_amount) /
            Number(this.zjData.quotation_amount)) *
          100
        ).toFixed(2);
      }
      this.tjqdhtVisible = this.addDialogVisible;
    },
  },
  computed: {},
  mounted() { },
  methods: {
    // 签约报价比计算
    quotationRatioFunc() {
      if (
        !this.tjqdhtRuleForm.quotation_amount ||
        !this.tjqdhtRuleForm.contract_price
      )
        return;
      this.tjqdhtRuleForm.contract_quotation_ratio = (
        (Number(this.tjqdhtRuleForm.contract_price) /
          Number(this.tjqdhtRuleForm.quotation_amount)) *
        100
      ).toFixed(2);
    },
    // 收款账户列表
    getCompanyList(account_type) {
      companyApi
        .getCompanyList({
          page: 1,
          num: 9999,
          keyword: "",
          account_type,
        })
        .then((res) => {
          console.log(res, account_type == 1 ? "公司列表" : "收款账户");
          if (res.code == 200) {
            this.companyOptions = res.data.list;
          } else {
            this.$message.warning(res.message);
          }
        })
        .catch((err) => {
          this.$message.warning(err.message);
        });
    },
    // 提交签订合同
    tjqdhtCancel(formName) {
      this.tjqdhtRuleForm = {
        remark: "",
        signing_date: "",
        signing_company_id: "",
        contract_commencement_date: "",
        contract_completion_date: "",
        duration_days: "",
        quotation_amount: "",
        contract_price: "",
        contract_file: [],
        contract_quotation_ratio: "",
      };
      this.$nextTick(() => {
        this.$refs[formName].clearValidate();
        this.$emit("onClose", true);
      });
    },
    tjqdhtDataFunc(e, type) {
      let tjqdhtRuleForm = this.tjqdhtRuleForm;
      if (type == "start") {
        if (tjqdhtRuleForm.contract_commencement_date) {
          this.pickerOptions_ = {
            disabledDate(time) {
              return (
                time.getTime() <
                new Date(tjqdhtRuleForm.contract_commencement_date).getTime()
              );
            },
          };
        } else {
          tjqdhtRuleForm.contract_completion_date = "";
        }
      }
      if (
        tjqdhtRuleForm.contract_commencement_date &&
        tjqdhtRuleForm.contract_completion_date
      ) {
        const date1 = new Date(tjqdhtRuleForm.contract_commencement_date);
        const date2 = new Date(tjqdhtRuleForm.contract_completion_date);
        if (!this.compareDates(date1, date2)) {
          this.$message.warning("完工日期需晚于开工日期");
          type == "start"
            ? (tjqdhtRuleForm.contract_commencement_date = "")
            : (tjqdhtRuleForm.contract_completion_date = "");
          tjqdhtRuleForm.duration_days = "";
          this.tjqdhtRuleForm = tjqdhtRuleForm;
          return;
        }
        tjqdhtRuleForm.duration_days = this.daysBetween(date1, date2) + 1;
      }
      this.tjqdhtRuleForm = tjqdhtRuleForm;
    },
    tjqdhtChangeFile(file, list, type) {
      let tjqdhtRuleForm = this.tjqdhtRuleForm;
      tjqdhtRuleForm.contract_file = [file];
      this.tjqdhtRuleForm = tjqdhtRuleForm;
    },
    tjqdhtFileRemove(file, list, type) {
      let tjqdhtRuleForm = this.tjqdhtRuleForm;
      tjqdhtRuleForm.contract_file = list;
      this.tjqdhtRuleForm = tjqdhtRuleForm;
    },
    tjqdhtSubmit(formName) {
      let tjqdhtRuleForm = this.tjqdhtRuleForm;
      console.log(tjqdhtRuleForm, "提交合同信息参数");
      let signing_company_name = "";
      let companyOptions = this.companyOptions;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let index = companyOptions.findIndex((item) => {
            return item.id == tjqdhtRuleForm.signing_company_id;
          });
          signing_company_name = companyOptions[index].account_name;
          this.diaLoading = true;
          let formdata = new FormData();
          formdata.append(
            "data",
            JSON.stringify({
              project_id: this.project_id,
              remark: tjqdhtRuleForm.remark,
              signing_date: tjqdhtRuleForm.signing_date,
              signing_company_id: tjqdhtRuleForm.signing_company_id,
              signing_company_name,
              contract_commencement_date:
                tjqdhtRuleForm.contract_commencement_date,
              contract_completion_date: tjqdhtRuleForm.contract_completion_date,
              duration_days: tjqdhtRuleForm.duration_days,
              quotation_amount: tjqdhtRuleForm.quotation_amount,
              contract_price: tjqdhtRuleForm.contract_price,
              contract_quotation_ratio: tjqdhtRuleForm.contract_quotation_ratio,
            })
          );
          tjqdhtRuleForm.contract_file.forEach((item) => {
            formdata.append("contract_file[]", item.raw);
          });
          projectApi
            .contractAward(formdata)
            .then((res) => {
              console.log(res, "提交合同信息");
              this.diaLoading = false;
              if (res.code == 200) {
                this.$emit("onSuccess", true);
              }
              this.$message({
                type: res.code == 200 ? "success" : "warning",
                message: res.code == 200 ? "处理成功" : res.message,
              });
            })
            .catch((err) => {
              this.diaLoading = false;
              this.$message({
                type: "warning",
                message: err.message,
              });
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    compareDates(date1, date2) {
      return date1.getTime() - date2.getTime() < 0;
    },
    daysBetween(date1, date2) {
      const oneDay = 24 * 60 * 60 * 1000; // 每天的毫秒数
      const firstTime = date1.getTime();
      const secondTime = date2.getTime();

      return Math.round(Math.abs((firstTime - secondTime) / oneDay));
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>